package com.qf.smsplatform.service.Impl;
/*2021/10/26*/

import com.qf.smsplatform.constans.ResultCode;
import com.qf.smsplatform.dto.R;
import com.qf.smsplatform.dto.UserDto;
import com.qf.smsplatform.exception.QueryDataException;
import com.qf.smsplatform.mapper.TAdminUserMapper;
import com.qf.smsplatform.pojo.CheckType;
import com.qf.smsplatform.pojo.TAdminUser;
import com.qf.smsplatform.service.TAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

/**
 * @YuTao
 */
@Service
@Transactional
public class TAdminUserServiceImpl implements TAdminUserService {

    private TAdminUserMapper tAdminUserMapper;
    @Autowired
    public void settAdminUserMapper(TAdminUserMapper tAdminUserMapper) {
        this.tAdminUserMapper = tAdminUserMapper;
    }

    @Override
    public TAdminUser login(UserDto user) {


        if(user.isNull(CheckType.ADD)){//调用的是user内封装的判断方法
            //对于错误的数据直接抛出异常，没有必要进行下一步的数据库查询
            throw new QueryDataException("用户名或者密码错误",ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //调用业务进行用户信息的查询
        TAdminUser userDto = tAdminUserMapper.selectUserByUsercode(user.getUsercode());
        if(userDto==null){//没有查询到用户，为了避免空指针异常，直接进行抛出
            throw new QueryDataException("用户名或者密码错误",ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //将传递过来的代码转化为MD5
        String digest = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        //与数据库中查询到的密码MD5进行比较
        if(!userDto.getPassword().equalsIgnoreCase(digest)){//两个密码不相等
            throw new QueryDataException("用户名或者密码错误",ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //中间还有一些判断用户状态信息的步骤，例如用户处于删除、封号状态等
        return userDto;
    }
}
